package verification

import BaseViewModel
import LoadingStatus
import ObjectsRepository
import android.util.Log
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
import my.models.ComponentUi
import my.models.ComputerUi
import verification.models.VerificationEvent
import verification.models.VerificationViewState

class VerificationViewModel(
    private val repository: ObjectsRepository
) : BaseViewModel<VerificationViewState, VerificationEvent>(initialState = VerificationViewState()) {

    override fun obtainEvent(event: VerificationEvent) {
        when (event) {
            is VerificationEvent.Verify -> verify(event.serial)
        }
    }

    private fun verify(serial: String) {
        updateState {
            it.copy(
                serial = serial,
                loadingStatus = LoadingStatus.Loading
            )
        }
        viewModelScope.launch {
            repository.computerBySerialNumber(serial)
                .onSuccess { computer ->
                    repository.verifyComputer(computer.id)
                        .onSuccess {
                            updateState {
                                it.copy(
                                    loadingStatus = LoadingStatus.FullyLoad,
                                    isVerified = true,
                                    verifiedObject = ComputerUi.fromComputer(computer)
                                )
                            }
                        }
                }
                .onFailure { tt ->
                    Log.d("DATA", "Error: ${tt.message}")
                    repository.componentBySerialNumber(serial)
                        .onSuccess { component ->
                            repository.verifyComponent(component.id)
                                .onSuccess {
                                    updateState {
                                        it.copy(
                                            loadingStatus = LoadingStatus.FullyLoad,
                                            isVerified = true,
                                            verifiedObject = ComponentUi.fromComponent(component)
                                        )
                                    }
                                }
                                .onFailure { t ->
                                    Log.d("DATA", "Error: ${t.message}")
                                    updateState { it.copy(loadingStatus = LoadingStatus.Error(t.message)) }
                                }
                        }
                        .onFailure { t ->
                            Log.d("DATA", "Error: ${t.message}")
                            updateState { it.copy(loadingStatus = LoadingStatus.Error(t.message)) }
                        }
                }
        }
    }
}